package io.geekidea.boot.warehousentry.uitl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 * java时间类
 *
 * @author mc2
 *
 */
public class JTime {
    static String dateFormat = "yyyy-MM-dd";
    static SimpleDateFormat format = new SimpleDateFormat(dateFormat);

    /**
     * 获取两个日期之间所有的日期
     * @param date1
     * @param date2
     * @return
     */
    public static ArrayList days(String date1, String date2) {
        ArrayList L = new ArrayList();
        if (date1.equals(date2)) {
            System.out.println("两个日期相等!");
            return L;
        }

        String tmp;
        if (date1.compareTo(date2) > 0) { // 确保 date1的日期不晚于date2
            tmp = date1;
            date1 = date2;
            date2 = tmp;
        }

        tmp = format.format(str2Date(date1).getTime());

        int num = 0;
        while (tmp.compareTo(date2) <= 0) {
            L.add(tmp);
            num++;
            tmp = format.format(str2Date(tmp).getTime() + 3600 * 24 * 1000);
        }

        if (num == 0)
            System.out.println("两个日期相邻!");
        return L;
    }

    private static Date str2Date(String str) {
        if (str == null)
            return null;

        try {
            return format.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 判断是否闰年
     *
     * @param year
     * @return
     */
    public static boolean isLeapYear(int year) {
        return (year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0));
    }

    /**
     * 一个月有几天
     *
     * @param year
     * @param month
     * @return
     */
    public static int dayInMonth(int year, int month) {
        boolean yearleap = isLeapYear(year);
        int day;
        if (yearleap && month == 2) {
            day = 29;
        } else if (!yearleap && month == 2) {
            day = 28;
        } else if (month == 4 || month == 6 || month == 9 || month == 11) {
            day = 30;
        } else {
            day = 31;
        }
        return day;
    }

}
